package logic

import (
	"Junior_two/subject/order/orderrpc/pb/orderRpc"
	"context"
	"fmt"
	"github.com/astaxie/beego/validation"
	"net/http"

	"Junior_two/subject/order/orderapi/internal/svc"
	"Junior_two/subject/order/orderapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.Createrequest) (resp *types.Createresponse, err error) {
	// todo: add your logic here and delete this line
	valid := validation.Validation{}
	valid.Required(req.UserId, "userId").Message("用户ID不可以为空")
	valid.Required(req.GoodId, "goodId").Message("商品ID不可以为空")
	valid.Required(req.Count, "count").Message("购买数量不可以为空")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			return &types.Createresponse{
				Msg:  v.Message,
				Code: http.StatusResetContent,
			}, nil
		}
	}
	fmt.Println(req.UserId)
	res, err := l.svcCtx.OrderServer.Create(l.ctx, &orderRpc.CreateRequest{
		UserId: req.UserId,
		GoodId: req.GoodId,
		Count:  req.Count,
	})
	if err != nil {
		return &types.Createresponse{
			Msg:  err.Error(),
			Code: http.StatusResetContent,
		}, nil
	}
	if res.Code != http.StatusOK {
		return &types.Createresponse{
			Msg:  res.Msg,
			Code: res.Code,
		}, nil
	}

	return &types.Createresponse{
		Msg:  res.Msg,
		Code: res.Code,
	}, nil

}
